package com.zhugang.week04;

import java.util.Stack;

/**
 * @program algorithms
 * @description: reversePrint
 * @author: chanzhugang
 * @create: 2022/06/15 20:50
 */
public class ReversePrint {

    /**
     * 剑指offer 06. 从尾到头打印链表
     *
     * @param head
     * @return
     */
    public int[] reversePrint(ListNode head) {
        // 遍历链表将节点数据放入栈中； 遍历栈将栈中数据弹出放入数组
        Stack<Integer> stack = new Stack<>();
        ListNode p = head;
        while (p != null) {
            stack.push(p.val);
            p = p.next;
        }
        int[] res = new int[stack.size()];
        int i = 0;
        while (!stack.isEmpty()) {
            res[i] = stack.pop();
            i++;
        }
        return res;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}